const Koa = require('koa')
const app = new Koa();
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const jwt = require('./middleware/loginAuth')
const RespModel = require('./model/RespModel')
const indexRouter = require('./router/index')
const userRouter = require('./router/user');
onerror(app)
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
//jwt验证授权
app.use(jwt);
//类似AOP中间件
app.use(async (cxt, next) => {
  try {
    const start = new Date();
    await next();
    const ms = new Date() - start
    console.log(`${cxt.method}${cxt.url}-${ms}ms`)
  } catch (err) {
    cxt.body = new RespModel(err.message).error();
  }

})
// app.use('/',router);
app.use(indexRouter.routes(), indexRouter.allowedMethods())
app.use(userRouter.routes(), userRouter.allowedMethods())
app.on('error', (err, ctx) => {
  console.log('server error', err);
  ctx.res.writeHead(200, {
    'content-Type': 'application/json'
  });
  if (err.name && err.name === 'UnauthorizedError') {
    ctx.res.end(JSON.stringify(new RespModel('授权未通过').success()));

  } else {
    ctx.res.end(JSON.stringify(new RespModel(err.message).error()));
    return;
  }

})
const server = app.listen(8001, () => {
  console.log(`服务启动中。。。http://localhost:${server.address().port}`)
})